
package com.rt.schedulenew.utils.jwt.util;
import java.util.Date;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
public class JWTUtil
{
    private long expireTime;
    private String aesKey;
    
    private JWTUtil() {
        this.expireTime = 1800000L;
        this.aesKey = "aes_key";
    }
    
    public JWTUtil builder(final long expireTime, final String aesKey) {
        final JWTUtil jwtUtil = new JWTUtil();
        jwtUtil.setExpireTime(expireTime);
        jwtUtil.setAesKey(aesKey);
        return jwtUtil;
    }
    
    public boolean verify(final String token, final String userId, final String aes_key) {
        try {
            final Algorithm algorithm = Algorithm.HMAC256(aes_key);
            final JWTVerifier verifier = JWT.require(algorithm).withClaim("userId", userId).build();
            final DecodedJWT jwt = verifier.verify(token);
            return true;
        }
        catch (Exception exception) {
            return false;
        }
    }
    
    public String getUserId(final String token) {
        try {
            final DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userId").asString();
        }
        catch (JWTDecodeException e) {
            return null;
        }
    }
    
    public String sign(final String userId, final String aes_key) {
        final Date date = new Date(System.currentTimeMillis() + this.expireTime);
        final Algorithm algorithm = Algorithm.HMAC256(aes_key);
        return JWT.create().withClaim("userId", userId).withExpiresAt(date).sign(algorithm);
    }
    
    public long getExpireTime() {
        return this.expireTime;
    }
    
    public void setExpireTime(final long expireTime) {
        this.expireTime = expireTime;
    }
    
    public String getAesKey() {
        return this.aesKey;
    }
    
    public void setAesKey(final String aesKey) {
        this.aesKey = aesKey;
    }
}
